/**
 * 登录状态管理
 */
import {mainOssSignature,userOssSignature,oemOssSignature} from "@/api/creatCenter/material";
import { formatMenus, toTreeData, formatTreeData } from 'ele-admin';
import { USER_MENUS } from '@/config/setting';
import { getUserInfo } from '@/api/layout';
import {getMerchantQuery,query} from "@/api/agent/pointAllocation";
import {listRoleMenus, updateRoleMenus} from "@/api/system/role";
import store from "@/store";
import {getMenuRoutes} from "@/router/routes";
import router from "@/router";

export default {
  namespaced: true,
  state: {
    // 当前登录用户信息
    info: null,
    // 当前登录用户的菜单
    menus: null,
    // 当前登录用户的权限
    authorities: [],
    // 当前登录用户的角色
    roles: []
  },
  mutations: {
    // 设置登录用户的信息
    setUserInfo(state, info) {
      state.info = info;
    },
    // 设置登录用户的菜单
    setMenus(state, menus) {
      state.menus = menus;
    },
    // 设置登录用户的权限
    setAuthorities(state, authorities) {
      state.authorities = authorities;
    },
    // 设置登录用户的角色
    setRoles(state, roles) {
      state.roles = roles;
    }
  },
  actions: {
    /**
     * 请求用户信息、权限、角色、菜单
     */
    async fetchUserInfo({ commit }) {
      const result = await getUserInfo().catch(() => {});
      if (!result) {
        return {};
      }
      let parms={}
      // console.log("登录result",result)
      if(result.merchantId){
        localStorage.setItem('username', result.username)// 存储 “username”
        localStorage.removeItem('indexData'); //清除缓存的查询代理数据，主要用于 “抖音cookie和抖音待用户发布” 的菜单显示
        // localStorage.removeItem('menus');  // 清除缓存的菜单数组
        let merchantId={ id: result.merchantId }
        parms= merchantId
        await getMerchantQuery(parms)
          .then((data) => {
            if(data.data != null){
              localStorage.setItem('indexData', JSON.stringify(data.data))// 存储 “系统图标等”
            }
          })
          .catch((e) => {
            this.$message.error(e);
          });

        // 查询角色权限
        let info = localStorage.getItem('indexData') ? JSON.parse(localStorage.getItem('indexData')) : {};
        let list=[]
        var arrNew=[];
        let ids= []
        if(!localStorage.getItem('menus')){
          await listRoleMenus({roleId: 16})  // 商家端id，如果总端的菜单管理‘商家端’被删除，则需要重新赋值
            .then((data) => {
              let cookieInfo={}   //D音cookie发布
              let userInfo={}   //用户库
              let empolyeesInfo={}   //D音代员工发布
              for(let i=0;i<data.length;i++){
                if(data[i].path=='/matrixManage/releaseManage/tiktok'){
                  cookieInfo=data[i]
                  data[i].checked=true
                }
                if(data[i].path=='/matrixManage/accountManage/userLibrary'){
                  userInfo=data[i]
                  data[i].checked=true
                }
                if(data[i].path=='/matrixManage/releaseManage/tiktokEmployees'){
                  empolyeesInfo=data[i]
                  data[i].checked=true
                }
              }
              list = data.filter(item=> {
                return item.checked
              })
              ids=list.map((d) => d.menuId)
              console.log("ids",ids,ids.length)
              if(info && info.toCookieReleased==1){
                //  如果是cookie，用户库和cookie发布存在，代用户发布则不存在
                ids.forEach((value,index,array)=>{
                  if(value == 166){
                    array.splice(index,1)
                  }
                })
              }
              if(info && info.toBeReleased==1){
                ids.forEach((value,index,array)=>{
                  if(value == 107 || value == 105){
                    array.splice(index,1)
                  }
                })
              }
              if(!info || info.toCookieReleased!=1&&info.toBeReleased!=1){
                ids.forEach((value,index,array)=>{
                  if(value == 107 || value == 105 || value == 166){
                    array.splice(index,1)
                  }
                })
              }

              console.log("ids222222",ids,ids.length)
              // 1.抖音h5 2.抖音无痕（cookie）_toCookieReleased 3.抖音代员工_toBeReleased 4.快手、
              /*if(info && info.toCookieReleased==1){
                //  如果是cookie，用户库和cookie发布存在，代用户发布则不存在
                list.forEach((value,index,array)=>{
                  if(value.path == empolyeesInfo.path){
                    array.splice(index,1)
                  }
                })
                console.log("list33333333",list)

              }
              if(info && info.toBeReleased==1){
                list.forEach((value,index,array)=>{
                  console.log("value.path",value.path,'cookieInfo.path',cookieInfo.path)
                  if(value.path !=cookieInfo.path && value.path != userInfo.path){
                    console.log("进入==========")
                    arrNew.push(value);
                  }})
                console.log("newArrlis4444444444",arrNew)
              }
              if(!info || info.toCookieReleased!=1&&info.toBeReleased!=1){
                list.forEach((value,index,array)=>{
                  if(value.path !=empolyeesInfo.path && value.path !=cookieInfo.path && value.path != userInfo.path){
                    arrNew.push(value);
                  }})
                console.log("newArrs55555555555",arrNew)
              }*/
            })
            .catch((e) => {
              this.$message.error(e.message);
            });
        }
        else{
          ids.push(localStorage.getItem('menus'))
          // console.log("进入缓存ids",ids,'11',localStorage.getItem('menus'))
        }
        // console.log("ids11111111111",ids)
        // let indexValue=info && info.toCookieReleased==1 ? list : arrNew

        /* 修改角色权限 */
        // await  updateRoleMenus({roleId: 16, ids: indexValue.map((d) => d.menuId)})
        // if(ids.length<24 || ids.length>28){
        if(ids.length<35 || ids.length>45){
          console.log('超出隐藏角色权限最大个数/最小个数ids',ids)
          ids= [92, 93, 95, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 166, 112, 113,114,130,160,157,158,159]
        }
        else{
          await updateRoleMenus({roleId: 16, ids: ids})
            .then((msg) => {
              console.log("修改角色权限=======",msg)
              localStorage.setItem('menus', ids)// 存储 “username”
            })
            .catch((e) => {
              this.$message.error(e.message);
            });
        }
      }
      //oem端
      if(result.oemId){
        localStorage.removeItem('indexData');
        let oemId={ oemId: result.oemId }
        parms= oemId
        await query(parms)
          .then((data) => {
            if(data.data != null){
              localStorage.setItem('indexData', JSON.stringify(data.data))// 存储 “系统图标等”
            }
          })
          .catch((e) => {
            this.$message.error(e);
          });
      }
      localStorage.removeItem('ossUrl'); //清除缓存的查询代理数据，主要用于 “抖音cookie和抖音待用户发布” 的菜单显示
      const queryOss = result.merchantId ? userOssSignature : result.oemId ? oemOssSignature : mainOssSignature
      // 获取文件上传签名数据
      const dataInfo = await queryOss()
      console.log("dataInfo",dataInfo)
      if(dataInfo && dataInfo.host){
        localStorage.setItem('ossUrl', dataInfo.host+'/')// 存储 “上传图片oss” 地址
      }
      console.log("进入获取文件后1111111111")

      // 用户信息
      commit('setUserInfo', result);
// 用户权限
      const authorities =
        result.authorities
          ?.filter((d) => !!d.authority)
          ?.map((d) => d.authority) ?? [];
      commit('setAuthorities', authorities);
// 用户角色
      const roles = result.roles?.map((d) => d.roleCode) ?? [];
      commit('setRoles', roles);
// 用户菜单, 过滤掉按钮类型并转为 children 形式
      const { menus, homePath } = formatMenus(
        USER_MENUS ??
        toTreeData({
          data: result.authorities?.filter((d) => d.menuType !== 1),
          idField: 'menuId',
          parentIdField: 'parentId'
        })
      );
      commit('setMenus', menus);   // 加载菜单

      return { menus, homePath };
    },
    /**
     * 更新用户信息
     */
    setInfo({ commit }, value) {
      commit('setUserInfo', value);
    },
    /**
     * 更新菜单的badge
     */
    setMenuBadge({ commit, state }, { path, value, color }) {
      const menus = formatTreeData(state.menus, (m) => {
        if (path === m.path) {
          return {
            ...m,
            meta: {
              ...m.meta,
              badge: value,
              badgeColor: color
            }
          };
        }
        return m;
      });
      commit('setMenus', menus);
    }
  },

};
